package com.sat.client

import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.navigation.NavOptions
import androidx.navigation.findNavController
import com.sat.client.databinding.ActivityMainBinding
import com.sat.common.base.BaseActivity
import com.sat.common.base.NoViewModel

class MainActivity : BaseActivity<NoViewModel, ActivityMainBinding>() {
    private val pagesToShowTabs = listOf(R.id.mainFragment)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
    }

    override fun layoutId(): Int {
        return R.layout.activity_main
    }

    override fun initView(savedInstanceState: Bundle?) {
        setupNavController()
    }

    override fun initData() {

    }

    override fun initListener() {

    }

    private fun setupNavController() {
        val navController = findNavController(R.id.nav_host_fragment_content_main)

        // 控制是否显示底部Tab的
        navController.addOnDestinationChangedListener { _, destination, _ ->
            val visibility = if (destination.id in pagesToShowTabs) View.VISIBLE else View.GONE
            mBinding?.apply {
                tabLayout.visibility = visibility
                separator.visibility = visibility
            }


        }

        // Tab切换
        mBinding?.tabLayout?.observeIndexChange { fromIndex, toIndex, reselect, fromUser ->
            if (fromUser) {
                navigateToTabDestination(toIndex)
            }
        }

    }

    private fun navigateToTabDestination(tabIndex: Int) {
        val destinationId = when (tabIndex) {
            0 -> R.id.mainFragment
//            1 -> R.id.mineFragment
            // 2 -> R.id.yetAnotherFragment
            // ... 其他index对应的destinationId
            else -> return
        }


        navigateToDestinationWithoutBackStack(destinationId)
    }

    private fun navigateToDestinationWithoutBackStack(destinationId: Int) {
        val navOptions = NavOptions.Builder()
            .setPopUpTo(R.id.nav_graph, true)
            .build()
        findNavController(R.id.nav_host_fragment_content_main).navigate(
            destinationId,
            null,
            navOptions
        )
    }
}